<template>
  <div>
    <span v-if="showDate" @click="date_range.show = true">{{ start ? (start + " ~ " + end) : '请选择日期' }}</span>
    <van-calendar
      v-model="date_range.show"
      :min-date="date_range.minDate"
      :max-date="date_range.maxDate"
      :default-date="currentValue"
      type="range"
      color="#1989fa"
      @confirm="selectDate"
    />
  </div>
</template>

<script>
export default {
  props: {
    showDate: {
      type: Boolean,
      default: () => true,
    },  
    start: {
      type: String,
    },
    end: {
      type: String,
    },
  },
  data() {
    return {
      date_range: {
        show: false,
        minDate: new Date(2000, 0, 1),
        maxDate: new Date(2030, 0, 31),
      },
    };
  },
  computed: {
    currentValue: {
      get() {
        return [new Date(this.start), new Date(this.end)];
      },
      set(newVal) {
        console.log(newVal);
        this.$emit("update:start", newVal[0]);
        this.$emit("update:end", newVal[1]);
        return newVal;
      },
    },
  },
  onMounted(){
    console.log(this.currentValue)
  },
  methods: {
    formatDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      month = Number(month) < 10 ? "0" + month : month;
      day = Number(day) < 10 ? "0" + day : day;
      return year + "-" + month + "-" + day;
    },
    selectDate(date) {
      const [start, end] = date;
      this.date_range.show = false;
      this.currentValue = [this.formatDate(start), this.formatDate(end)];
      this.$emit('change', this.currentValue);
    },
  },
};
</script>